#include "cli.h"
#include "graphics.h"
#include <windows.h>
#include <stdio.h>

const int Graphics::RED = FOREGROUND_RED;
const int Graphics::GREEN = FOREGROUND_GREEN;
const int Graphics::BLUE = FOREGROUND_BLUE;
const int Graphics::INTENSITY = FOREGROUND_INTENSITY;
const int Graphics::BACK_RED = BACKGROUND_RED;
const int Graphics::BACK_GREEN = BACKGROUND_GREEN;
const int Graphics::BACK_BLUE = BACKGROUND_BLUE;
const int Graphics::BACK_INTENSITY = BACKGROUND_INTENSITY;
const int Graphics::DEFAULT = Graphics::RED|Graphics::GREEN|Graphics::BLUE;
const int Graphics::BLACK = 0;
const int Graphics::DARK_GRAY = Graphics::INTENSITY;
const int Graphics::GRAY = Graphics::DEFAULT;
const int Graphics::WHITE = Graphics::DEFAULT|Graphics::INTENSITY;
const int Graphics::BACK_GRAY = Graphics::BACK_RED|Graphics::BACK_GREEN|Graphics::BACK_BLUE;

void Graphics::render(){
	setCursorPosition(0,0);
	int color = -1, oldColor = -1;
	int total = width*height;
	int x = 0, y = 0;
	// render only what has changed since the last draw
	int cursorx = -1, cursory = -1, cursorColor = -1;
	for(int i = 0; i < total; ++i)
	{
		if(buffer[i] != lastbuffer[i] || this->color[i] != lastcolor[i])
		{
			if(x != cursorx || y != cursory){
				setCursorPosition(x, y);
				cursorx = x; cursory = y;
				cursorColor = -1;
			}
			if(this->color[i] != cursorColor){
				cursorColor = this->color[i];
				setColor(cursorColor);
			}
			putchar(buffer[i]);
			cursorx++;
		}
		x++;
		if(x >= width){
			x = 0;
			setColor(DEFAULT);
			oldColor = DEFAULT;
			putchar('\n');
			y++;
		}
	}
	for(int i = 0; i < total; ++i)
	{
		lastbuffer[i] = buffer[i];
		lastcolor[i] = this->color[i];
	}
}